import React, { useState, useEffect } from "react";
import "./step1.css";
import Index from "../../../components/bg";
import { useNavigate } from "react-router";

const Step1 = () => {
  const [formData, setFormData] = useState(() => {
    const savedData = localStorage.getItem("registerStep1");
    return savedData
      ? JSON.parse(savedData)
      : {
          phone: "",
          verificationCode: ["", "", "", ""],
          email: "",
          password: "",
        };
  });
  const [countdown, setCountdown] = useState(0);
  const [showPassword, setShowPassword] = useState(false);

  const navigate = useNavigate();

  // 处理验证码输入
  const handleCodeChange = (index, value) => {
    if (!/^\d*$/.test(value)) return; // 只允许输入数字

    const newCode = [...formData.verificationCode];
    newCode[index] = value;

    setFormData((prev) => ({
      ...prev,
      verificationCode: newCode,
    }));

    // 自动跳转到下一个输入框
    if (value && index < 3) {
      const nextInput = document.querySelector(
        `input[name="code-${index + 1}"]`
      );
      if (nextInput) nextInput.focus();
    }
  };

  // 获取验证码
  const handleGetCode = () => {
    if (countdown === 0 && formData.phone) {
      setCountdown(60);
      // 模拟5秒后收到验证码
      setTimeout(() => {
        const mockVerificationCode = Math.floor(
          1000 + Math.random() * 9000
        ).toString(); // 模拟的验证码
        console.log("收到验证码:", mockVerificationCode);

        // 自动填充验证码
        const newCode = mockVerificationCode.split("");
        setFormData((prev) => ({
          ...prev,
          verificationCode: newCode,
        }));
      }, 5000);
    }
  };

  // 检查验证码是否已填写
  const hasVerificationCode = formData.verificationCode.join("").length === 4;

  const handleNext = () => {
    // 保存数据到 localStorage
    localStorage.setItem("registerStep1", JSON.stringify(formData));
    navigate("/step2");
  };

  useEffect(() => {
    let timer;
    if (countdown > 0) {
      timer = setInterval(() => {
        setCountdown((prev) => prev - 1);
      }, 1000);
    }
    return () => clearInterval(timer);
  }, [countdown]);

  // 在组件加载时获取数据
  useEffect(() => {
    const savedData = localStorage.getItem("registerData");
    if (savedData) {
      setFormData(JSON.parse(savedData));
    }
  }, []);

  return (
    <div className="verification-wrapper">
      <Index />
      <div className="verification-container">
        <div className="step-text1">STEP 1/4</div>
        <h3>验证手机号</h3>

        <div className="form-group">
          <label>手机号</label>
          <div className="phone-input-container">
            <input
              type="tel"
              value={formData.phone}
              onChange={(e) =>
                setFormData((prev) => ({ ...prev, phone: e.target.value }))
              }
              placeholder="15800000000"
              maxLength={11}
            />
            <button
              className={`verify-code-btn ${
                hasVerificationCode ? "disabled" : ""
              }`}
              onClick={handleGetCode}
              disabled={hasVerificationCode || countdown > 0} // 当有验证码或倒计时时禁用
            >
              {countdown > 0 ? `${countdown}s` : "获取验证码"}
            </button>
          </div>
        </div>

        <div className="form-group">
          <label>短信验证码</label>
          <div className="verification-code-inputs">
            {formData.verificationCode.map((code, index) => (
              <input
                key={index}
                type="text"
                name={`code-${index}`}
                maxLength={1}
                value={code}
                onChange={(e) => handleCodeChange(index, e.target.value)}
              />
            ))}
          </div>
        </div>

        {countdown > 0 && (
          <div className="verification-message">
            <span className="info-icon">ℹ️</span>
            <span>
              短信验证码已发送至您的手机号码 {formData.phone}，有效期至
              {countdown}
            </span>
          </div>
        )}

        <div className="form-group">
          <label>Email</label>
          <input
            type="email"
            value={formData.email}
            onChange={(e) =>
              setFormData((prev) => ({ ...prev, email: e.target.value }))
            }
            placeholder="youliao@gmail.com"
          />
        </div>

        <div className="form-group">
          <label>输入密码</label>
          <div className="password-input-container">
            <input
              type={showPassword ? "text" : "password"}
              value={formData.password}
              onChange={(e) =>
                setFormData((prev) => ({ ...prev, password: e.target.value }))
              }
              placeholder="········"
            />
            <span
              className="password-toggle"
              onClick={() => setShowPassword(!showPassword)}
            >
              {showPassword ? "👁️" : "👁️"}
            </span>
          </div>
        </div>
      </div>
      <button
        className="next-button"
        onClick={() => {
          handleNext();
        }}
      >
        下一步 <span>→</span>
      </button>
    </div>
  );
};

export default Step1;
